//
//  EFengDisCussCreateController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/1/21.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "EFengDisCussCreateController.h"
#import "EFengLatestContactSelectCell.h"
#import "SettingNormalCell.h"
#import "ContactVC.h"
#import "UIImageView+WebCache.h"
#import "CContactModel.h"
#import "CDepartmentModel.h"
#import "CDepartmentMgr.h"
#import "CXmppRequestMgr.h"
#import "CContactMgr.h"
#import "NSArray+PinYin.h"
#import "GroupMemberDetailVC.h"
#import "CFileModel.h"
#import "ChildHoodService.h"
#import "CFolderMgr.h"
#import "CMessageMgr.h"
#import "CMessageModel.h"
#import "MicroDef.h"
#import "JKAlertDialog.h"
#import "IMFowardContactController.h"
#import "ChildHoodMessage.h"
#import "CGroupMgr.h"
#import "CGroupModel.h"
#import "CHChatRoomBase.h"
#import "UIBarButtonItem+category.h"
#import "IMSearchDisplayController.h"
#import "EFengCreateDisDepartMentController.h"
#import "UIImage+ImageWithColor.h"
#import "MBProgressHUD+WZ.h"
#import "CHChatRoomBase.h"
#import "CGroupMemberMgr.h"
#import "CGroupMemberModel.h"
#import "CMessageDraftMgr.h"
#import "CMessageDraft.h"
#import "UIUtil.h"
#import "CXmppMgr.h"
#import "MBProgressHUD+WZ.h"
#import "CGroupMgr.h"

#define KSECTIONHEIGHT 35.0f
#define KNORMALCELLHEIGHT 60.0f


@interface EFengDisCussCreateController ()<UITableViewDelegate, UITableViewDataSource, EFengLatestContactSelectCellDelegate, UISearchBarDelegate, UISearchDisplayDelegate>
{
    NSMutableArray *_searchAllFirstLetter;
    NSMutableArray *_searchSectionListArray;
    UISearchBar *_searchBar;
    UISearchDisplayController *_searchDisplayController;
    CContactMgr *_contactMgr;
    CGroupMemberMgr *_groupMemMgr;
    CGroupMgr *_groupMgr;
    CGroupModel *_newGroup;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *contactList;
@property (nonatomic, strong) NSArray *groupMemberArray;
WeakProperty UIButton *bottomButton;
StrongProperty NSArray *selectedArray;
StrongProperty CContactModel *curUser;
@end
@implementation EFengDisCussCreateController


- (NSMutableArray *)contactList
{
    if (_contactList == nil) {
        _contactList = [NSMutableArray array];
    }
    return _contactList;
}



- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPCREATEDISCUSSION object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}
//UISearchDisplayDelegate
- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IsIOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createSuccess:) name:K_XMPPCREATEDISCUSSION object:nil];
    //bug 6082 fixed by 荣则兵  begin
    _contactMgr = [[CContactMgr alloc] init];
    _groupMemMgr = [[CGroupMemberMgr alloc] init];
    _groupMgr = [[CGroupMgr alloc] init];
    
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationItem setNewTitleCenter:@"   "];
    
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:nil title:@"取消" target:self sel:@selector(cancel) titleFont:Font18 titleColor:WhiteColor];
    CAccountModel *model = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    self.curUser = [[[CContactMgr alloc] init] loadContactWithUserCode:model.userName];
    
    _tableView = [[UITableView alloc] init];
    _tableView.frame = CGRectMake(0, 44.0f, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64.0f - 44.0f - 90.0f);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.sectionIndexBackgroundColor = ClearColor;
    _tableView.sectionIndexTrackingBackgroundColor = ClearColor;
    
    
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    _searchBar.backgroundImage = [UIImage strechingWithImageName:@"BG-search"];
    //test 研发中心搜素
    _searchBar.placeholder = @"搜索";
    _searchBar.delegate = self;
    // 添加 searchbar 到 headerview
    [self.view addSubview:_searchBar];
    
    _searchDisplayController = [[IMSearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
    
    // searchResultsDataSource 就是 UITableViewDataSource
    _searchDisplayController.searchResultsDataSource = self;
    // searchResultsDelegate 就是 UITableViewDelegate
    _searchDisplayController.searchResultsDelegate = self;
    _searchDisplayController.delegate = self;
    _searchDisplayController.searchResultsTableView.sectionIndexColor = RGBCOLOR(0x64, 0x64, 0x64);
    _searchDisplayController.searchResultsTableView.sectionIndexBackgroundColor = ClearColor;
    _searchDisplayController.searchResultsTableView.sectionIndexTrackingBackgroundColor = ClearColor;
    
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    _searchAllFirstLetter = [NSMutableArray arrayWithCapacity:5];
    _searchSectionListArray = [NSMutableArray arrayWithCapacity:5];

    
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    
    UIButton *bottomButton = [UIButton buttonWithType:UIButtonTypeCustom];
    bottomButton.layer.cornerRadius = 3.0f;
    bottomButton.layer.masksToBounds = YES;
    [bottomButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    
    [bottomButton addTarget:self action:@selector(createDiscussList) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bottomButton];
    bottomButton.frame = CGRectMake(10.0f, HARDWARE_SCREEN_HEIGHT - 64.0f - 40.0f - 25.0f, HARDWARE_SCREEN_WIDTH - 20.0f, 40.0f);
    [bottomButton setBackgroundImage:[UIImage createImageWithColor:RGBCOLOR(89, 136, 243) withBounds:bottomButton.bounds] forState:UIControlStateNormal];
    self.bottomButton = bottomButton;
    
    if (self.group) {
        NSArray *array = [_groupMemMgr loadAllGroupMemberByGroupID:self.group.GroupId];
            NSMutableArray *arrayM = [NSMutableArray array];
            for (CGroupMemberModel *groupModel in array) {
                CContactModel *contact = [_contactMgr loadContactWithUserId:groupModel.UserId];
                if (contact) {
                    if (contact.isDel == 1) {
                        [arrayM addObject:contact];
                    } else {
                        [_groupMemMgr delGroupMember:groupModel];
                    }
                }
            }
            self.group.UserNum = arrayM.count;
            [_groupMgr updateGroup:self.group];
        self.groupMemberArray = arrayM;
    }
    
}

- (void)createDiscussList
{
    if ([CXmppMgr shareInstance].reachability.currentReachabilityStatus == NotReachable) {
        [MBProgressHUD showError:@"网络异常"];
        return;
    }
    if (self.group == nil) {
        if (self.selectedArray.count > 1) {
//            CGroupModel *group = [[CGroupModel alloc] init];
            _newGroup = [[CGroupModel alloc]init];
            _newGroup.isShow = NO;
            _newGroup.groupType = 1;
            NSMutableString *groupName = [NSMutableString string];
            for (CContactModel *contact in self.selectedArray) {
                
                [groupName appendFormat:@"%@、",contact.UserName];
            }
            
            [groupName appendString:self.curUser.UserName];
            
            _newGroup.GroupName = groupName;
            _newGroup.GroupNotice = self.curUser.UserName;
            _newGroup.GroupIntroduction = self.curUser.UserName;
            [[CXmppRequestMgr shareInstance] creatDiscussWithGroup:_newGroup curUser:self.curUser];
            [UIUtil addMBProgressViewTitle:@"创建中..." inView:self.view alpha:1 failureTitle:@"创建失败"];
//            [self cancel];
            
        } else if (self.selectedArray.count == 1) {
            
            [self dismissViewControllerAnimated:NO completion:^{
                CContactModel *contact = self.selectedArray.lastObject;
                CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
                chat.member = contact;
                chat.group = nil;
                
                UINavigationController *rotNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                UIViewController *vc = rotNav.childViewControllers[1];
                [rotNav popToViewController:vc animated:NO];
                
                [rotNav pushViewController:chat animated:YES];
                
            }];
            
        }
 
    } else {
        NSInteger memCount = self.group.UserNum + self.selectedArray.count;
        if (memCount > 50) {
            [MBProgressHUD showError:@"已达50人上限"];
            return;
        } else {
            
            [[CXmppRequestMgr shareInstance] addDiscussMemberwithGroup:self.group members:self.selectedArray curUser:nil];
            [self cancel];

        }
    }
    
}
// bug fixed by lixu
-(void)createSuccess:(NSNotification*)notification
{
    [UIUtil hideMBProgressViewForView:self.view];
    [self dismissViewControllerAnimated:NO completion:^{
        CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
        chat.member = nil;
        NSString *groupID = notification.userInfo[@"groupid"];
        //bug 9270 fixed by lixu
        chat.group = [[[CGroupMgr alloc]init]loadGroup:groupID];
        UINavigationController *rotNav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        UIViewController *vc = rotNav.childViewControllers[1];
        [rotNav popToViewController:vc animated:NO];
        
        [rotNav pushViewController:chat animated:YES];

    }];
}
- (void)cancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    if (IsIOS7) {
        [self.navigationController.navigationBar setBarTintColor:RGBCOLOR(44, 170, 253)];
    } else {
        [self.navigationController.navigationBar setTintColor:RGBCOLOR(44, 170, 253)];
    }
     self.bottomButton.frame = CGRectMake(10.0f, HARDWARE_SCREEN_HEIGHT - 64.0f - 40.0f - 25.0f, HARDWARE_SCREEN_WIDTH - 20.0f, 40.0f);
    _tableView.frame = CGRectMake(0, 44.0f, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64.0f - 44.0f - 90.0f);
    
    
    self.selectedArray = [_contactMgr loadAllSelectedContact];
    if (self.selectedArray.count > 0) {
        [self.bottomButton setTitle:[NSString stringWithFormat:@"邀请(%zd)",self.selectedArray.count] forState:UIControlStateNormal];
        self.bottomButton.enabled = YES;
    } else {
        [self.bottomButton setTitle:@"邀请" forState:UIControlStateNormal];
        self.bottomButton.enabled = NO;
    }

    [self.contactList removeAllObjects];
    NSArray *array = [[[CMessageMgr alloc] init] loadmessageList];
    NSArray *draftArray = [[[CMessageDraftMgr alloc]init] loadAllmessageDraft];
    //bug fixed by lixu
    [draftArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(CMessageDraft *obj, NSUInteger idx, BOOL *stop) {
        if (obj.GroupId.length > 3) {
            
        } else {
            BOOL isMember = NO;
            CContactModel *model = [_contactMgr loadContactWithUserId:obj.FriendUserId];
            if (model) {
                for (CContactModel *contact in self.groupMemberArray) {
                    if ([model.UserID isEqualToString:contact.UserID]) {
                        isMember = YES;
                        break;
                    }
                }
                if (!isMember && ![model.UserID isEqualToString:self.curUser.UserID] && model.isDel) {
                    
                    [self.contactList addObject:model];
                }
            }
        }
    }];
    [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(CMessageModel *obj, NSUInteger idx, BOOL *stop) {
        if (obj.GroupId.length > 3) {
            
        } else {
            BOOL isMember = NO;
            CContactModel *model = [_contactMgr loadContactWithUserId:obj.FriendUserId];
            if (model) {
                for (CContactModel *contact in self.groupMemberArray) {
                    if ([model.UserID isEqualToString:contact.UserID]) {
                        isMember = YES;
                        break;
                    }
                }
                if (!isMember && ![model.UserID isEqualToString:self.curUser.UserID] && model.isDel) {
                    
                    [self.contactList addObject:model];
                    for (CMessageDraft *draft in draftArray) {
                        if ([draft.FriendUserId isEqualToString:obj.FriendUserId]) {
                            [self.contactList removeObject:model];
                        }
                    }

                }
            }
        }
            }];

    [_tableView reloadData];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger rows = 0;
    if (_tableView == tableView) {
        switch (section) {
            case 0:
                rows = 1;
                break;
            case 1:
                rows = self.contactList.count;
                break;
            default:
                rows = 0;
                break;
        }
        
    } else {
        NSArray *rowArray = _searchSectionListArray[section];
        rows = [rowArray count];
    }
    return rows;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView              // Default is 1 if not implemented
{
    if (_tableView == tableView) {
        return 2;
    } else {
        return _searchSectionListArray.count;
    }
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tableView) {
        if (indexPath.section == 0) {
            
            static NSString *NormalCellIdentifier = @"SettingNormalCell";
            SettingNormalCell *normalCell = [tableView dequeueReusableCellWithIdentifier:NormalCellIdentifier];
            if (normalCell == nil) {
                normalCell = [[[NSBundle mainBundle] loadNibNamed:@"SettingNormalCell" owner:self options:nil] objectAtIndex:0];
            }
            
            normalCell.rightArrow.hidden = NO;
            [normalCell.titleLabel setText:[self titleName:indexPath]];
            normalCell.icon.layer.cornerRadius = 5.0f/2;
            normalCell.icon.layer.masksToBounds = YES;
            [normalCell.icon setImage:[UIImage imageNamed:@"icon-organization"] forState:UIControlStateNormal];
            return normalCell;
            
        } else {
            
            CContactModel *contact = self.contactList[indexPath.row];
            
            EFengLatestContactSelectCell *groupMemberCell = [EFengLatestContactSelectCell eFengLatestContactSelectCellWithTableview:tableView];
            groupMemberCell.eFengLatestContactSelectCellDelegate = self;
            groupMemberCell.cellIndexPath = indexPath;
            groupMemberCell.tableView = tableView;
            [groupMemberCell.headerIcon sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:contact.UserID]] placeholderImage:[UIImage imageNamed:@"80-80"]];
            //        [groupMemberCell.titleLabel setText:@"测试名字"];
            [groupMemberCell.userNameLabel setText:contact.UserName];
            NSInteger rows = [tableView numberOfRowsInSection:indexPath.section];
            if(indexPath.row == rows - 1)
            {
                [groupMemberCell.seperatorLine setHidden:NO];
                groupMemberCell.shortLine.hidden = YES;
            } else {
                groupMemberCell.seperatorLine.hidden = YES;
                groupMemberCell.shortLine.hidden = NO;
            }
            groupMemberCell.selectIcon.selected = contact.isSelected;
            return groupMemberCell;
            
        }
    } else {
        
        NSArray *rowArray = _searchSectionListArray[indexPath.section];
        CContactModel *contact = rowArray[indexPath.row];
        
        EFengLatestContactSelectCell *groupMemberCell = [EFengLatestContactSelectCell eFengLatestContactSelectCellWithTableview:tableView];
        groupMemberCell.eFengLatestContactSelectCellDelegate = self;
        groupMemberCell.cellIndexPath = indexPath;
        groupMemberCell.tableView = tableView;
        
        
        [groupMemberCell.headerIcon sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:contact.UserID]] placeholderImage:[UIImage imageNamed:@"80-80"]];
        //        [groupMemberCell.titleLabel setText:@"测试名字"];
        [groupMemberCell.userNameLabel setText:contact.UserName];
        NSInteger rows = [tableView numberOfRowsInSection:indexPath.section];
        if(indexPath.row == rows - 1)
        {
            [groupMemberCell.seperatorLine setHidden:NO];
            groupMemberCell.shortLine.hidden = YES;
        } else {
            groupMemberCell.seperatorLine.hidden = YES;
            groupMemberCell.shortLine.hidden = NO;
        }
        groupMemberCell.selectIcon.selected = contact.isSelected;
        return groupMemberCell;

        
    }
}

-(NSString *)titleName:(NSIndexPath *)indexPath
{
    NSString *title = nil;
    
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                    title = @"组织架构";
                    break;
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            title = @"最近联系人";
        }
            break;
        default:
            break;
    }
    return title;
}



#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    if (_tableView == tableView) {
        
        CGFloat height = 0.01f;
        switch (section) {
            case 1:
                height = KSECTIONHEIGHT;
                break;
            default:
                break;
        }
        return height;
    } else {
        return KSECTIONHEIGHT;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    CGFloat height = 0.01f;
    switch (section) {
        case 1:
            height = 0.01f;
            break;
        default:
            break;
    }
    return height;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    UIView *headerView = nil;
    if (_tableView == tableView) {
        if(section == 0)
        {
            return headerView;
        }
        headerView = [[UIView alloc] init];
        headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, KSECTIONHEIGHT);
        headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
        UIView *beginLine = [[UIView alloc] init];
        beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
        [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
        [headerView addSubview:beginLine];
        
        UIView *endLine = [[UIView alloc] init];
        endLine.frame = CGRectMake(0, KSECTIONHEIGHT-0.5, tableView.frame.size.width, 0.5);
        [endLine setBackgroundColor:KSEPERATORLINECOLOR];
        [headerView addSubview:endLine];
        
        UILabel *label = [[UILabel alloc] init];
        [label setText:@"最近联系人"];
        [label setTextColor:RGBCOLOR(0x92, 0x92, 0x92)];
        label.frame = CGRectMake(15, 1, 200, KSECTIONHEIGHT-1);
        [headerView addSubview:label];

    } else {
        headerView = [[UIView alloc] init];
        headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, KSECTIONHEIGHT);
        headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
        UIView *beginLine = [[UIView alloc] init];
        beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
        [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
        [headerView addSubview:beginLine];
        
        UIView *endLine = [[UIView alloc] init];
        endLine.frame = CGRectMake(0, KSECTIONHEIGHT-0.5, tableView.frame.size.width, 0.5);
        [endLine setBackgroundColor:KSEPERATORLINECOLOR];
        [headerView addSubview:endLine];
        
        UILabel *label = [[UILabel alloc] init];
        label.text = _searchAllFirstLetter[section];
        [label setTextColor:RGBCOLOR(0x92, 0x92, 0x92)];
        label.frame = CGRectMake(15, 1, 200, KSECTIONHEIGHT-2);
        [headerView addSubview:label];

    }
    
    return headerView;
}


- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (_tableView == tableView) {
        return nil;
    } else{
        return _searchAllFirstLetter;
    }
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSInteger count = 0;
    if(tableView == _tableView)
    {
        count = index;
    } else {
        count = index;
    }
    return count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = KNORMALCELLHEIGHT;
    
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView == _tableView) {
        if (indexPath.section == 0 && indexPath.row == 0) {
            [self showContactVC];
        }
    }
}

- (void)eFengLatestContactSelectCellDidselectWithIndexPath:(NSIndexPath *)indexPath tableView:(UITableView *)tableView
{
    
    if (_tableView == tableView) {
        __block CContactModel *contact = self.contactList[indexPath.row];
        if (!contact.isSelected) {
            NSInteger memCount = 0;
            memCount = self.groupMemberArray.count + self.selectedArray.count;
            if (memCount >= 50) {
                [MBProgressHUD showError:@"已达50人上限"];
                return;
            }
        }
        contact.isSelected = !contact.isSelected;
        
        [_contactMgr updateContactSelectedWithContact:contact seleceted:contact.isSelected];
        [_tableView reloadData];
 
    } else {
        
        NSArray *rowArray = _searchSectionListArray[indexPath.section];
        __block CContactModel *contact = rowArray[indexPath.row];
        
        if (!contact.isSelected) {
            NSInteger memCount = 0;
            memCount = self.groupMemberArray.count + self.selectedArray.count;
            if (memCount >= 50) {
                [MBProgressHUD showError:@"已达50人上限"];
                return;
            }
        }

        
        contact.isSelected = !contact.isSelected;
        
        [_contactMgr updateContactSelectedWithContact:contact seleceted:contact.isSelected];
        [_searchDisplayController.searchResultsTableView reloadData];
    }
    self.selectedArray = [_contactMgr loadAllSelectedContact];
    if (self.selectedArray.count > 0) {
        [self.bottomButton setTitle:[NSString stringWithFormat:@"邀请(%zd)",self.selectedArray.count] forState:UIControlStateNormal];
        self.bottomButton.enabled = YES;
    } else {
        [self.bottomButton setTitle:@"邀请" forState:UIControlStateNormal];
        self.bottomButton.enabled = NO;
    }
}

-(void)showContactVC
{
    NSArray *deps = [[[CDepartmentMgr alloc] init] loadDepartments:@"0"];
    CDepartmentModel *dep = deps.lastObject;
   EFengCreateDisDepartMentController *departDetail = [[EFengCreateDisDepartMentController alloc] initWithDepartId:dep.DEPTID];
    departDetail.group = self.group;
    [self.navigationController pushViewController:departDetail animated:YES];
    
}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [_searchSectionListArray removeAllObjects];
    [_searchAllFirstLetter removeAllObjects];
    NSArray *contactArray = [_contactMgr searchContactWithSeachStr:searchText];
    if (contactArray == nil) {
        return;
    }
    
    NSMutableArray *arrayM = [NSMutableArray array];
    __block BOOL isMem = NO;
    CContactModel *current = [[[CContactMgr alloc]init] loadCurContact];
    [contactArray enumerateObjectsUsingBlock:^(CContactModel *obj, NSUInteger idx, BOOL *stop) {
        isMem = NO;
        for (CContactModel *contact in self.groupMemberArray) {
            if ([obj.UserID isEqualToString:contact.UserID]) {
                isMem = YES;
                break;
            }
        }
        //bug 8667 fixed by lixu
        if ([obj.UserID isEqualToString:current.UserID]) {
            isMem = YES;
        }
        if (!isMem) {
            [arrayM addObject:obj];
        }
    }];
    _searchAllFirstLetter = [NSArray IndexArray:arrayM];
    _searchSectionListArray = [NSArray LetterSortArray:arrayM];
    
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar                     // called when text starts editing
{
    searchBar.showsCancelButton = YES;
    for(id cc in [_searchDisplayController.searchBar subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
    }
    
}

//隐藏搜索为空时cell的分割线
//bug 8510 fixed by lixu
- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView NS_DEPRECATED_IOS(3_0,8_0){
    [tableView setContentInset:UIEdgeInsetsZero];
    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
    tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
}
//bug 9506 fixed by lixu
-(void)searchDisplayController:(UISearchDisplayController *)controller willHideSearchResultsTableView:(UITableView *)tableView
{
    self.selectedArray = [_contactMgr loadAllSelectedContact];
    if (self.selectedArray.count > 0) {
        [self.bottomButton setTitle:[NSString stringWithFormat:@"邀请(%zd)",self.selectedArray.count] forState:UIControlStateNormal];
        self.bottomButton.enabled = YES;
    } else {
        [self.bottomButton setTitle:@"邀请" forState:UIControlStateNormal];
        self.bottomButton.enabled = NO;
    }
    
    [self.contactList removeAllObjects];
    NSArray *array = [[[CMessageMgr alloc] init] loadmessageList];
    NSArray *draftArray = [[[CMessageDraftMgr alloc]init] loadAllmessageDraft];
    //bug fixed by lixu
    [draftArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(CMessageDraft *obj, NSUInteger idx, BOOL *stop) {
        if (obj.GroupId.length > 3) {
            
        } else {
            BOOL isMember = NO;
            CContactModel *model = [_contactMgr loadContactWithUserId:obj.FriendUserId];
            if (model) {
                for (CContactModel *contact in self.groupMemberArray) {
                    if ([model.UserID isEqualToString:contact.UserID]) {
                        isMember = YES;
                        break;
                    }
                }
                if (!isMember && ![model.UserID isEqualToString:self.curUser.UserID] && model.isDel) {
                    
                    [self.contactList addObject:model];
                }
            }
        }
    }];
    [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(CMessageModel *obj, NSUInteger idx, BOOL *stop) {
        if (obj.GroupId.length > 3) {
            
        } else {
            BOOL isMember = NO;
            CContactModel *model = [_contactMgr loadContactWithUserId:obj.FriendUserId];
            if (model) {
                for (CContactModel *contact in self.groupMemberArray) {
                    if ([model.UserID isEqualToString:contact.UserID]) {
                        isMember = YES;
                        break;
                    }
                }
                if (!isMember && ![model.UserID isEqualToString:self.curUser.UserID] && model.isDel) {
                    
                    [self.contactList addObject:model];
                    for (CMessageDraft *draft in draftArray) {
                        if ([draft.FriendUserId isEqualToString:obj.FriendUserId]) {
                            [self.contactList removeObject:model];
                        }
                    }
                    
                }
            }
        }
    }];
    
    [_tableView reloadData];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString

{ for(UIView *subview in controller.searchResultsTableView.subviews) {
    
    if([subview isKindOfClass:[UILabel class]]) {
        
        [(UILabel*)subview setText:@"未找到匹配的信息"];
        
    }
    
}
    return YES;
}


- (void) searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller NS_DEPRECATED_IOS(3_0,8_0)
{
    UIView *topView = controller.searchBar.subviews[0];
    
    for (UIView *subView in topView.subviews) {
        
        if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
            
            UIButton * cancelButton = (UIButton*)subView;
            
            [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
            
        }
        
    }
}

@end
